package com.classtest.classtestdemo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.classtest.classtestdemo.bean.DbOrder;
import com.classtest.classtestdemo.bean.DbUser;
import com.classtest.classtestdemo.service.DbGoodsService;
import com.classtest.classtestdemo.service.DbOrderService;
import com.classtest.classtestdemo.utlis.PKGeneration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class DbOrderController {
    @Autowired
    DbOrderService dbOrderService;
    @Autowired
    DbGoodsService dbGoodsService;

    @RequestMapping("/addOrder")
    public String buyNowAction(@RequestBody String json, HttpSession session){
        Map<String,Object> result = new HashMap<>();
        try{
            DbUser user = (DbUser) session.getAttribute("user");
            if(user != null){
                DbOrder dbOrder = JSONObject.parseObject(json,DbOrder.class);
                dbOrder.setAddress(user.getAddress());
                dbOrder.setOid(PKGeneration.INSTANCE.nextId());
                dbOrder.setBuyerId(user.getId());
                dbOrder.setStatus("0");
                dbOrderService.insertOrder(dbOrder);
                int count = Integer.parseInt(dbOrder.getCount());
                String gsId = dbOrder.getGsId();
                dbGoodsService.UpdateCountByGsId(gsId,count);
                result.put("reFlag","ok");
            }else {
                result.put("reFlag","error");
                result.put("msg","没有登录");
            }
        }catch (Exception e){
            result.put("error",e.toString());
        }

        return JSON.toJSONString(result);
    }
}
